package com.ftg.learn.springbootmq.work.consumer;

import com.alibaba.fastjson2.JSON;
import com.ftg.learn.springbootmq.work.entity.StudentEntity;
import com.ftg.learn.springbootmq.work.mapper.StudentMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * 消息消费者
 *
 * @author 布衣
 * @since 2025-08-08
 */
@Component
public class MessageConsumer {

    @Resource
    private StudentMapper studentMapper;

    /**
     * 处理字符串消息
     *
     * @param message 消息内容
     * @param channel 通道
     * @param message 原始消息对象
     * @throws IOException IO异常
     */
    @RabbitListener(queues = "work.queue")
    public void handleStringMessage(Map<String,Object> message, Channel channel, Message messageObj) throws IOException {
        deal(message,channel,messageObj);
    }

    /**
     * 处理结构化消息
     *
     * @param message 消息内容
     * @param channel 通道
     * @param messageObj 原始消息对象
     * @throws IOException IO异常
     */
    @RabbitListener(queues = "work.queue")
    public void handleStructuredMessage(Map<String, Object> message, Channel channel, Message messageObj) throws IOException {
        deal(message,channel,messageObj);
    }


    private void deal(Map<String, Object> map, Channel channel, Message messageObj) throws IOException {
        try {
            int n =0;
            if (map.get("operator").equals("add")) {
                StudentEntity stu = JSON.parseObject(map.get("body").toString(), StudentEntity.class);
                n = studentMapper.insert(stu);
            }else if(map.get("operator").equals("update")){
                StudentEntity stu = JSON.parseObject(map.get("body").toString(), StudentEntity.class);
                n = studentMapper.updateById(stu);
            }else{
                String body = map.get("body").toString();
                n = studentMapper.deleteById(body);
            }

            // 手动确认消息
            if(n>=0){
                channel.basicAck(messageObj.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (Exception e) {
            // 拒绝消息并重新入队
            channel.basicNack(messageObj.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
